<?php
namespace Auth;

/**
 * 与用户Model高耦合
 */
class Auth
{
    const ECRYPT_METHOD = 'DES-CBC'; // 加密方式
    private $_user;
    /* 用户对应的model */
    private $_model;
    private $_session;
    private static $_instances;

    public function __construct($module)
    {
        $this->_model = $module;
        $this->_session = 'auth_' . $module;
    }

    /**
     * 登录
     *
     * @return void
     */
    public function login($user)
    {
        $this->_user = $user;
        session($this->_session, $user);
        if ($user['remember_token'] !== '') {
            $this->remember($user);
        }
    }

    /**
     * 自动登录 
     *
     * @return void
     */
    public function autoLogin()
    {
        $cookie = cookie($this->_session);
        if ($cookie) {
            $sercretKey = C('SECRET_KEY');
            $auth = openssl_decrypt($cookie, self::ECRYPT_METHOD, $sercretKey);
            $auth = json_decode($auth, true);
            $now = time();
            if ($now < $auth['expired_at']
                && $auth['user_agent'] === $_SERVER['HTTP_USER_AGENT']) {
                $user = D($this->_model)->find($auth['id']);
                if ($user['remember_token'] === $auth['remember_token']) {
                    D($this->_model)->login($user, true);
                    return true;
                }
            }
        }
        return false;

        
    }

    /**
     * 判断是否已经登录
     *
     * @return boolean
     */
    public function hasLogined()
    {
        $user = session($this->_session);
        return !empty($user);
    }

    /**
     * 注销
     *
     * @return void
     */
    public function logout()
    {
        if ($this->hasLogined()) {
            session($this->_session, null);
            cookie($this->_session, null);

        }
        return true;
    }

    /**
     * 返回当前登录用户
     *
     * @return array
     */
    public function user()
    {
        return $this->hasLogined() ? session($this->_session) : false;
    }

    /**
     * 生成
     * @param string $username
     * @param integer $expire 有效时长（秒）
     * @return void
     */
    public function remember($user, $expired = 60 * 60 * 24)
    {
        $data = [
            'user_agent' => $_SERVER['HTTP_USER_AGENT'],
            'username' => $user['username'],
            'expired_at' => time() + $expired,
            'remember_token' => $user['remember_token'],
        ];

        $cookieStr = json_encode($data);
        $sercretKey = C('SECRET_KEY');
        $cookieStr = openssl_encrypt($cookieStr, self::ECRYPT_METHOD, $sercretKey);
        cookie($this->_session, $cookieStr, ['expire' => $expired]);
    }

    /**
     * 是否有记住的信息，这里简单并没有检测数据合法性
     *
     * @return boolean
     */
    public function isRemembered()
    {
        $cookie = cookie($this->_session);
        return !empty($cookie);
    }

    /**
     * 获取单例对象
     *
     * @param string $model，可在config.php配置
     * @return object
     */
    public static function auth($model = null)
    {
        $model = $model ?: C(strtoupper(MODULE_NAME) . '_AUTH_MODEL');
        if (!$_instances[$model] instanceof self) {
            $instance = new self($model);
            self::$_instances[$model] = $instance;
        }
        return self::$_instances[$model];
    }

}